import axios, {AxiosInstance, AxiosRequestConfig, AxiosResponse} from 'axios';
import {urls} from "@/config";
import {ElMessage} from "element-plus";

class HttpClient {
    private instance: AxiosInstance;

    constructor() {
        this.instance = axios.create({
            baseURL: urls,
            timeout: 10000,
        });

        this.instance.interceptors.request.use(
            (config) => {
                // 在发送请求之前做些什么
                return config;
            },
            (error) => {
                // 对请求错误做些什么
                return Promise.reject(error);
            }
        );

        this.instance.interceptors.response.use(
            (response) => {
                // 对响应数据做点什么
                return response;
            },
            (error: any) => {
                // 对响应错误做点什么
                let message = '' as string
                const status = error.response.code as number
                switch (status) {
                    case 401:
                        message = 'token过期'
                        break
                    case 403:
                        message = '无权访问'
                        break
                    case 404:
                        message = '请求地址错误'
                        break
                    case 500:
                        message = '服务器出现戳五'
                        break
                    default:
                        message = '网路出现问题'
                }
                ElMessage({
                    type: 'error',
                    message
                })
                return Promise.reject(error);
            }
        );
    }

    public async get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
        const response = await this.instance.get<T>(url, config);
        return response.data;
    }

    public async post<T>(
        url: string,
        data?: any,
        config?: AxiosRequestConfig
    ): Promise<T> {
        const response = await this.instance.post<T>(url, data, config);
        return response.data;
    }

    public async put<T>(
        url: string,
        data?: any,
        config?: AxiosRequestConfig
    ): Promise<T> {
        const response = await this.instance.put<T>(url, data, config);
        return response.data;
    }

    public async delete<T>(
        url: string,
        config?: AxiosRequestConfig
    ): Promise<T> {
        const response = await this.instance.delete<T>(url, config);
        return response.data;
    }
}

export default new HttpClient();
